<template>
  <div v-loading="loading">
    <!--预览数据-->
    <el-form ref="form" v-loading="loading" :model="form" :rules="paramsRules" class="dataForm" @submit.native.prevent>
      <!-- 动态参数  -->
      <div class="area-header mt-15">
        <span class="area-header-title">{{ $t('查询参数') }}</span>
      </div>
      <div v-if="mapObject && mapObject !== null && mapObject.length > 0" style="margin-top:10px">
        <el-form-item v-for="(item,index) in mapObject" :key="index" :rules="[{ required: true, message: $t('必填字段') }]">
          <div v-if="item.isShow === 'true'">
            <span slot="label">
              <span style="color: red; font-size: 16px;">*</span>
              <span>{{ $t(item.label) }}</span>
              <!-- <span v-if="defaultFormat.includes(item.format)">{{ item.templateLabel }}</span> -->
              <!--            <el-tooltip v-if="!defaultFormat.includes(item.format)" :content="item.sql" placement="top">-->
              <!--              <i class="el-icon-question" />-->
              <!--            </el-tooltip>-->
            </span>
            <div><el-input v-if="item.type === 'WB'" v-model="item.param" style="width: 100%" :placeholder="$t('请输入')" @keyup.enter.native="queryHandle" /></div>
            <div><Money v-if="item.type === 'JE'" v-model="item.param" style="width: 100%" :placeholder="$t('请输入')" /></div>
            <div><DatePicker v-if="item.type === 'RQ'" v-model="item.param" style="width: 100%" type="date" :placeholder="$t('请选择')" /></div>
            <div><UserSelect v-if="item.type === 'RY'" v-model="item.param" style="width: 100%" :placeholder="$t('请选择')" /></div>
            <div>
              <el-select
                v-if="item.type === 'ZB'"
                v-model="item.param"
                clearable
                :placeholder="$t('请选择')"
                style="width: 100%"
              >
                <el-option
                  v-for="result in queryResultObject[item.id]"
                  :key="result.value"
                  :label="$t(result.label)"
                  :value="result.value"
                />
              </el-select>
            </div>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="queryHandle">{{ $t('查询') }}</el-button>
        </el-form-item>
      </div>
    </el-form>
    <el-table v-loading="tableDataLoading" :data="previewData" style="width: 100%">
      <el-table-column v-for="(item, index) in tableColumns" :key="index" :prop="item.fieldName" min-width="200px" :label="item.title" :show-overflow-tooltip="true" tooltip-effect="darkTable" class="nowrapTable" />
    </el-table>
  </div>
</template>

<script>
import { getWordOnlineKeyWord, getResultByParamId } from '@/api/system/word/keyword/wordOnlineKeyWord'
import { previewSqlResult } from '@/api/system/search/searchSqlBase'

export default {
  components: {
  },
  data() {
    return {
      // 表单参数
      form: {},
      // 遮罩层
      loading: false,
      mapObject: undefined,
      tableDataLoading: false,
      previewData: [],
      tableColumns: [],
      paramsRules: {},
      queryResultObject: {}
    }
  },
  created() {
  },
  methods: {
    init(data) {
      this.loading = false
      this.form = {}
      this.mapObject = undefined
      this.previewData = []
      this.tableColumns = []
      this.paramsRules = {}
      this.queryResultObject = {}
      if (data != null && data.id !== undefined) {
        this.loading = true
        getWordOnlineKeyWord(data.id).then(async(response) => {
          this.form = response.data
          if (this.form.sqlScript) {
            await this.previewScriptBySql()
          }
          this.loading = false
        })
      }
    },
    previewScriptBySql: async function() {
      // 把里面所有的数字全部显示出来
      this.form.searchSql = this.form.sqlScript
      this.searchSqlBack = this.form.searchSql
      var sqlArray = this.form.searchSql.match(/[^{]+(?=})/g)
      if (this.form.searchSql === null || this.form.searchSql === '') {
        this.$message.error('sql脚本不能为空')
      } else if (sqlArray && sqlArray.length > 0) {
            // 查看是否有参数 有的话展示参数
          this.mapObject = this.form.paramsList
          if (this.mapObject) {
            // var tempKeyWord = []
            // 目的是让每种类型的输入框只展示一个.
            for (const item of this.mapObject) {
              if (!item.type) {
                this.msgError(this.$t('请先维护参数列表'))
              }
              // 如果是指标 先去查询下拉选项
              if (item.type === 'ZB') {
                await this.getQueryResult(item.id)
              }
                item.isShow = 'true'
            }
          }
          this.tableColumns = []
      } else {
        this.tableDataLoading = true
        await previewSqlResult(this.form).then((response) => {
          this.form.searchSql = this.searchSqlBack
          if (response.data) {
            this.previewData = response.data
              // 根据返回的数据动态生成表格列配置项
            if (this.previewData.length > 0) {
              this.previewOpen = true
              this.tableColumns = []
              Object.keys(this.previewData[0]).forEach((key) => {
                this.tableColumns.push({ fieldName: key, title: key })
              })
              this.$forceUpdate()
            } else {
              this.msgWarning(this.$t('未查询出数据!'))
            }
            this.tableDataLoading = false
          } else {
            this.msgError(this.$t('sql脚本异常!'))
          }
        })
      }
    },
    async queryHandle() {
      var flag = false
      var param = ''
      console.log('param')
      this.mapObject.forEach(item => {
        if (!item.param) {
          flag = true
        }
        param += item.value + '@' + item.param + '*'
      })
      console.log('param=' + param)
      if (flag) {
        this.msgError(this.$t('请输入必填项'))
      } else {
        this.tableDataLoading = true
        this.form.paramStr = param
        await previewSqlResult(this.form).then((response) => {
          this.form.searchSql = this.searchSqlBack
          if (response.data) {
            this.previewData = response.data
              // 根据返回的数据动态生成表格列配置项
            if (this.previewData.length > 0) {
              this.previewOpen = true
              this.tableColumns = []
              Object.keys(this.previewData[0]).forEach((key) => {
                this.tableColumns.push({ fieldName: key, title: key })
              })
              this.$forceUpdate()
            } else {
              this.msgWarning(this.$t('未查询出数据!'))
            }
            this.tableDataLoading = false
          } else {
            this.msgError(this.$t('sql脚本异常!'))
          }
        })
      }
    },
    async getQueryResult(id) {
      this.queryResultObject[id] = await this.getResultByParamInfo(id)
    },
    getResultByParamInfo(id) {
      // eslint-disable-next-line no-unused-vars
      return new Promise((resolve, reject) => {
        getResultByParamId(id).then((response) => {
          resolve(response.data.result)
        })
      })
    }
  }
}
</script>
<style scoped>
.codesql {
  font-size: 11pt;
  font-family: Consolas, Menlo, Monaco, Lucida Console, Liberation Mono,
    DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace, serif;
}
</style>
